package com.visionork.android.twe.model;

import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Episode implements Serializable, Crawler, Cacheable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Date date;
	private String title;
	private String urlLink;
	private ArrayList<Part> parts;

	public Episode() {
		parts = new ArrayList<Part>();
	}

	public Part getPart(String key) {
		for (Part part : parts) {
			if (part.getKey().equals(key)) {
				return part;
			}
		}
		return null;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public ArrayList<Part> getParts() {
		if (parts == null || parts.size() == 0) {
			Crawl();
		}

		return parts;
	}

	public void setParts(ArrayList<Part> parts) {
		this.parts = parts;
	}
	
	public static ArrayList<Part> CrawlHelper(String urlString) {
		ArrayList<Part> tmpParts = new ArrayList<Part>();
		try {
			Document doc = Jsoup.parse(new URL(urlString), 5000);
			
			Elements defaultElms = doc.getElementsByTag("span");
			for (Element elm : defaultElms) {
				if (elm.hasAttr("class")
						&& elm.attr("class").equals("contentlist") && elm.hasText()) {
					String href = urlString;
					String title = elm.text().trim();
					Part part = new Part();
					part.setTitle(title);
					part.setUrlLink(href);
					tmpParts.add(part);
				}
			}
			
			Elements elms = doc.getElementsByTag("a");
			for (Element elm : elms) {
				if (elm.hasAttr("class")
						&& elm.attr("class").equals("contentlist") && elm.hasText()) {
					String href = elm.attr("href");
					String title = elm.text().trim();
					Part part = new Part();
					part.setTitle(title);
					part.setUrlLink(href);
					tmpParts.add(part);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return tmpParts;
	}
	
	@Override
	public void Crawl() {
		parts = CrawlHelper(urlLink);
	}

	@Override
	public String getKey() {
		return urlLink;
	}

	@Override
	public boolean equals(Object obj) {
		return getKey().equals(((Episode) obj).getKey());
	}
	
	public void setUrlLink(String urlLink) {
		this.urlLink = urlLink;
	}

	public String getUrlLink() {
		return urlLink;
	}
}
